<!--
 * @Author: jingjingzheng 1742420988@qq.com
 * @Date: 2023-12-21 03:29:07
 * @LastEditors: jingjingzheng 1742420988@qq.com
 * @LastEditTime: 2023-12-31 03:04:26
 * @FilePath: \mdbj-ui\src\views\datamanager\roadsurface\addPanel.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-col :span="24" class="title-row">
      <span :style="{ color: theme }">| 新增 {{roadname}} 道路面</span>
    </el-col>
    <el-form id="elForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="92px">
      <el-row>
        <el-col :span="formcolwidth">
          <el-form-item label="道路编码" label-width="120px" prop="code">
            <el-input
              v-model="formData.code"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
      </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="道路功能" label-width="120px" prop="roadfunction">
            <el-select
              v-model="formData.roadfunction"
              placeholder="请选择道路功能"
              :disabled="iseditfunction"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="dict in dict.type.sys_roadfunction"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="路面材料" label-width="120px" prop="pavementmaterials">
            <el-select
              v-model="formData.pavementmaterials"
              placeholder="请选择路面材料"
              clearable
              :style="{ width: '100%' }"
              >
              <el-option
              v-for="dict in dict.type.sys_pavementmaterials" :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
          <el-form-item label="参考面积(m²)" label-width="120px" prop="ref_area">
            <el-input
              v-model="formData.ref_area"
              clearable
              :style="{ width: '100%' }"
              @input="formData.ref_area= formData.ref_area.replace(/[^\d|\.]/g, '')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="formcolwidth">
            <el-form-item label="备注" label-width="120px" prop="note">
              <el-input
                v-model="formData.note"
                clearable
                :style="{ width: '100%' }"
              ></el-input>
            </el-form-item>
        </el-col>
      </el-row>

        <el-form-item class="footer" size="large">
        <el-button type="primary" @click="submitForm" icon="el-icon-check">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" plain icon="el-icon-circle-close" @click="cancel">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import FeatureLayer from "@arcgis/core/layers/FeatureLayer";
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
export default {
  name: 'MdbjUiAddPanel',
  props: {
      mapview: { default: () => { } },
      paramObj: { default: () => { } },
    },
  inject: ["toggleComponent"],
  components: {
    FeatureLayer,
    Graphic,
    GraphicsLayer,
    Sketch,
  },
  dicts: [
    "sys_roadclass_js",
    "sys_cleancompany",
    "sys_roadfunction",
    "sys_pavementmaterials",
    "road_data_status",
  ],
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  data() {
    return {
        //新增道路面修改开关
        iseditfunction: false,
        // 必须给formData对象的属性设置对应空值，否则重置后无法输入数据
        formData: {
        // objectid: "",
        code: "",
        // name: "",
        // roadclass_js: "",
        // length: "",
        roadfunction: "",
        pavementmaterials: "",
        note: "",
        ref_area: "",
        data_status:"",
      },
      rules:{
      roadfunction: [
        { required: true, message: '请选择道路功能', trigger: 'blur' },
      ],
      pavementmaterials: [
        { required: true, message: '请选择路面材料', trigger: 'blur' },
      ],
      occupiedarea: [
        { required: false, message: '请输入占用面积', trigger: 'blur' },
      ],
      cleancompany: [
        { required: true, message: '请选择保洁公司', trigger: 'blur' },
      ],
      },
      // 列表宽度
      formcolwidth:24,
      roadcode:undefined,
      roadname:undefined,
      // 当前页道路中心线
      feature: undefined,
      featureLayer: undefined,
      // 当前页正在编辑的要素-道路面
      roadsurfacefeature: undefined,
      // 道路面要素图层url
      roadsurfacefeatureLayerUrl:
        window.mapConfig.operationLayers.featurelayers["roadsurfacelayer"].url,
      // 道路面图层视图
      roadsurfacelayerView: undefined,
      // 道路面要素图层
      roadsurfacefeatureLayer: undefined,
      // 当前页面田加空间位置信息
      selectedGraphic: undefined,
      // 当前页面田加空间位置信息
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      sketch: undefined,
      addGraphics: [],
      data_status: undefined,
      // 当前添加道路面跳转组件
      localname: undefined,
    };
  },

  activated() {
    let _self = this
    console.log(_self.paramObj)
    _self.initData();
    //重新加载道路面数据
    _self.initFeatureLayer();
  },
  deactivated() {
    let _self = this
    _self.clearGraphics();
    _self.clearData();
  },

  methods: {
    /**
     * @description: 初始化数据
     * @return {*}
     */
    initData(){
      let _self = this;
      _self.localname = this.paramObj.localname;
      _self.feature = this.paramObj.feature;
      _self.roadname = this.paramObj.feature.attributes.name;
      _self.formData.code = _self.feature.attributes.code;
      _self.formData.data_status = 1
      _self.roadcode = _self.feature.attributes.code;
      _self.roadsurfacefeatureLayer = _self.paramObj.roadsurfacefeatureLayer
    },
    /**
     * @description: 初始化roadsurfaceroadsurfacefeatureLayer
     * @return {*}
     */
    initFeatureLayer() {
      let _self = this;
      _self.mapview.map.add(_self.roadsurfacefeatureLayer,1);
      // 获取当前图层视图
      _self.mapview.whenLayerView(_self.roadsurfacefeatureLayer).then((layerView) => {
      // console.log("roadsurface layerView loaded");
      _self.roadsurfacelayerView = layerView;
      // 显示图形编辑面板
      _self.addGeometry();
      });
    },
    submitForm() {
      let _self = this;
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        if (_self.selectedGraphic == undefined) {
          _self.$message.error("请添加空间位置信息");
          return;
        }
        // 新增要素
        const status = "1";
        const attributes = {
          // objectid: _self.formData.objectid,
          code: _self.formData.code,
          roadfunction: _self.formData.roadfunction,
          ref_area: _self.formData.ref_area,
          // occupiedarea: _self.formData.occupiedarea,
          pavementmaterials: _self.formData.pavementmaterials,
          note: _self.formData.note,
          data_status: _self.formData.data_status,
          // name: _self.formData.name,
          // roadclass_js: _self.formData.roadclass_js,
          // cleancompany: _self.formData.cleancompany,
          // managementunit: _self.formData.managementunit,
          // startpoint: _self.formData.startpoint,
          // endpoint: _self.formData.endpoint,
        };
        const addFeature = new Graphic({
          geometry:
          _self.selectedGraphic == undefined
            ? ""
            : _self.selectedGraphic.geometry,
          attributes: attributes,
        });
        _self.roadsurfacefeatureLayer
          .applyEdits({
          addFeatures: [addFeature],
          })
          .then((editsResult) => {
          console.log(editsResult);
          if (_self.selectedGraphic)
            _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
          const objectId = editsResult.addFeatureResults[0].objectId;
          console.log(objectId);
          _self.$message.success("新增成功");
          _self.cancel();
          });
      });
    },
    // 添加空间位置
    addGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer({
        title: "道路面编辑图层",
      });
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline:false,
          polygon: true,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      _self.sketch.create();
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一个面，如果已创建的一个面，则不允许继续创建面。隐藏创建面按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
        }
      });
      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("update complete");
          if (event.graphics.length == 0) return;
          _self.selectedGraphic = event.graphics[0];
        }
      });
      _self.sketch.on("delete", (event) => {
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何点，就显示创建点按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },
    resetForm() {
      let _self = this;
      _self.formData.roadfunction = undefined;
      _self.formData.pavementmaterials = undefined;
      _self.formData.ref_area = undefined;
      _self.formData.note = undefined;
    },
    clearGraphics(){
      let _self = this;
      _self.addGraphics = [];
      // 删除临时图形
      _self.mapview.graphics.removeAll();
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      // 切换组件
      _self.mapview.map.remove(_self.roadsurfacefeatureLayer);
    },
    clearData(){
      let _self = this;
      // 重置输入表单
      _self.$refs["elForm"].resetFields();
      _self.roadcode = undefined;
    },
    cancel() {
      let _self = this;
      _self.clearGraphics();
      _self.clearData();
      const paramObj = {
        feature: _self.feature,
        activeName:"roadsurfacePanel"
      };
      this.toggleComponent(_self.localname,paramObj);
    },
  },
};
</script>

<style lang="less" scoped>

</style>
